#!/bin/bash
# author tyb


# 执行结果判断函数
function isgreen() {
    if [ $? -eq 0 ]; then
        echo -e "\e[32m$1==========>succeed\e[0m"
    else
        echo -e "\e[31m$1==========>failed\e[0m"
        # exit 1
    fi
}

# 网络测试函数
function network() {
    #超时时间
    local timeout=1

    #目标网站
    local target=www.baidu.com

    #获取响应状态码
    local ret_code
    ret_code=$(curl -I -s --connect-timeout ${timeout} ${target} -w "%{http_code}" | tail -n1)

    if [ "$ret_code" = "200" ]; then
        #网络畅通
        echo -e "\e[32m网络畅通==========>succeed\e[0m"
        return 0
    else
        #网络不畅通
        echo -e "\e[31m网络不畅通，请检查网络==========>succeed\e[0m"
        return 1
    fi

}

# 指定下载文件名为 docker-27.5.1.tgz 并保存到 /opt/ 目录下
wget -O /opt/docker-27.5.1.tgz https://download.docker.com/linux/static/stable/x86_64/docker-27.5.1.tgz > /dev/null 2>&1
isgreen "下载docker-27.5.1.tgz"

# 解压文件到 /opt/ 目录下
tar -zxvf /opt/docker-27.5.1.tgz -C /opt/ > /dev/null 2>&1
isgreen "解压docker-27.5.1.tgz" 

# 移动文件到 /usr/bin/ 目录下
mv /opt/docker/* /usr/bin/
isgreen "移动文件到 /usr/bin/ 目录下"

cat << EOF >> /etc/systemd/system/docker.service
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network.target

[Service]
ExecStart=/usr/local/bin/dockerd
ExecReload=/bin/kill -s HUP $MAINPID
Restart=always
TimeoutSec=0
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
EnvironmentFile=-/etc/default/docker

[Install]
WantedBy=multi-user.target
EOF
isgreen "创建docker.service文件"

# 重新加载 systemd 配置
systemctl daemon-reload > /dev/null 2>&1
isgreen "重新加载 systemd 配置"

# 启动 docker 服务
systemctl start docker > /dev/null 2>&1
isgreen "启动 docker 服务"

# 配置 docker 开机自启动
systemctl enable docker > /dev/null 2>&1
isgreen "配置 docker 开机自启动"